'''
Author: 奔跑的乌龟
email: 435327238@qq.com
'''

import time
import requests
from requests.api import get
from lxml import etree


class Request:
    # 请求链接
    url = ""

    # 请求头
    headers = {}

    # 请求体
    data = {}

    # 状态码
    status_Code = 200

    # 返回数据
    response = {}

    # 编码
    charset = ''

    # 请求标记
    request_sum = 0

    # 构造请求类
    def __init__(self, url, headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36"}, charset='utf-8' ):

        self.url = url
        self.headers = headers
        self.charset = charset
    
    # GET请求
    def get(self, data="" ):
        try:
            print("开始请求：" + self.url)
            reponse = requests.get(self.url,timeout=None, params=data)
            if reponse.status_code == 200:
                reponse.encoding = self.charset
                return reponse.text
            # 状态码503
            elif reponse.status_code == 503:
                self.reRuest(data)
            # 状态码404
            elif reponse.status_code == 404:
                raise RuntimeError(self.url + "请求链接不存在!") 
        # 状态码出现错误
        except BaseException as e:
            self.reRuest(data)

    # 重复请求
    def reRuest(self, data):
        # 重复请求
        if self.request_sum<3:
            self.request_sum = self.request_sum+1
            print("请求失败，正在进行第",self.request_sum,"次请求")
            time.sleep(3)
            self.get(data)
        else:
            print("连续三次获取失败,结束请求")
            raise RuntimeError(self.url + "连续三次请求错误") 